#! /usr/bin/perl -w
use integer;
use strict;
use base qw(Exporter);
use IO::Socket;
use Data::Dumper;
use Encode 'from_to';
use POSIX 'strftime';
use FindBin '$Bin';
use Math::BigInt;

our $MAGIC = "QV";
our $VER = 1;
our $SEQ = 1;
our $Proto = "tcp";

sub sock {
	my $app = shift;

    return new IO::Socket::INET(PeerAddr=>$app, Proto=>$Proto);
}

sub request {
	my ($app, $cmd, $data) = @_;

	my $sock = sock($app);

	my $request_send_timeout = 5;

	my $request_recv_timeout = 5;

	my ($sync, $ver, $len, $SEQ, $type, $code, $total, $offset);
    eval {
        $sock->setsockopt(SOL_SOCKET, SO_SNDTIMEO, pack('LL', $request_send_timeout, 0));
        $sock->setsockopt(SOL_SOCKET, SO_RCVTIMEO, pack('LL', $request_recv_timeout, 0));

        $sock->send($data);

        if ($Proto eq "udp") {
            $sock->recv($data, 4096);
        } else {
            $sock->recv($data, 28);
        }
        ($sync, $ver, $len, $SEQ, $type, $code, $total, $offset) = unpack("A2 n N N N N N N", $data);
        if ($Proto eq "udp") {
            $data = substr($data, 28, $len);
        } else {
            if ($len > 0) {
                my $left = $len;
                $data = "";
                while ($left > 0)
                {
                    my $piece;
                    $sock->recv($piece, $left);
                    last if length($piece) <= 0;
                    $left -= length($piece);
                    $data .= $piece;
                }
            } else {
                $data = "";
            }
        }
    };
	return ($code, $data);
}

	my $server = "192.168.56.101:6666";
	my $cmd="abc";
	my $data="abc_file";
	request($server, $cmd, $data);
